﻿using System.Security.Cryptography;
using System.Text;

namespace Wips.Infrastructure.Helpers
{
    public static class Rsa2Helper
    {
        public static string EncryptWithPublicKey(string data, string publicKey)
        {
            var rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(publicKey);

            List<string> encryptedDataList = new List<string>();

            int maxLength = 200;  // 计算最大明文长度

            for (int i = 0; i < data.Length; i += maxLength)
            {
                var dataToEncrypt = data.Substring(i, Math.Min(maxLength, data.Length - i));
                var dataBytes = Encoding.UTF8.GetBytes(dataToEncrypt);
                var encryptedBytes = rsa.Encrypt(dataBytes, false);
                encryptedDataList.Add(Convert.ToBase64String(encryptedBytes));
            }

            return string.Join("@@@", encryptedDataList) ;
        }

        public static string DecryptWithPrivateKey(string data, string privateKey)
        {
            var list = data.Split("@@@");
            var rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(privateKey);

            StringBuilder decryptedData = new StringBuilder();

            foreach (var chunk in list)
            {
                var dataBytes = Convert.FromBase64String(chunk);
                var decryptedBytes = rsa.Decrypt(dataBytes, false);
                decryptedData.Append(Encoding.UTF8.GetString(decryptedBytes));
            }

            return decryptedData.ToString();
        }

        /// <summary>
        /// 使用私钥对数据进行签名。
        /// </summary>
        /// <param name="data"></param>
        /// <param name="privateKey"></param>
        /// <returns></returns>
        public static string SignDataWithPrivateKey(string data, string privateKey)
        {
            var rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(privateKey);
            var dataBytes = Encoding.UTF8.GetBytes(data);
            var signedBytes = rsa.SignData(dataBytes, SHA256.Create());
            return Convert.ToBase64String(signedBytes);
        }

        /// <summary>
        /// 使用公钥验证数据的签名。
        /// </summary>
        /// <param name="data"></param>
        /// <param name="sign"></param>
        /// <param name="publicKey"></param>
        /// <returns></returns>
        public static bool VerifyDataWithPublicKey(string data, string sign, string publicKey)
        {
            var rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(publicKey);
            var dataBytes = Encoding.UTF8.GetBytes(data);
            var signBytes = Convert.FromBase64String(sign);
            return rsa.VerifyData(dataBytes, SHA256.Create(), signBytes);
        }
    }
}
